var addrbill = require('../../sys/sys_addr.js')
const app = getApp()

// 废弃
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    delivery_config:{
      type:Object,
      value:null
    },
    showselected: { // 属性名
      type: Boolean,
      value: true
    },
    selectdefault: { // 属性名
      type: Boolean,
      value: true
    },
    mode: {
      type: Number,
      default: 2
    },
    themcolor:{
      type:Object,
      default:{}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    navCur:0,
    selectaddr: {},
    isload: true,
    addrmodel: {},
    region: [],
    addrblock: true,
    addrlist: [],
    op: "result",
    CustomBar: app.globalData.CustomBar,
  },
  ready: function () {
    
 
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //底部下拉
    onReachBottom: function (e) {
      var that = this;
      this.getpagelist(that, -1);
    },
    chooseLocation(ev){
     
     var addform = this.selectComponent("#addform");
     addform.chooseLocation(ev)

    },
    leftclick() {
    

    },
    //列表
    getpagelist(that, rest, strwhere) {

      if (rest == 1) {
        that.setData({
          addrlist: []
        });
      }
      this.setData({ isload: true })
      addrbill.offset(that, rest).then(function (result) {
        var updatemdoel = {};
        if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
          if (rest == 1) {
            updatemdoel["addrlist"] = result["obj"]["modellist"];
          } else {
            if (result["obj"]["modellist"].length > 0) {
              updatemdoel["addrlist"] = that.data.addrlist.concat(result["obj"]["modellist"]);
            }
          }
        }
        updatemdoel["isload"] = false
        that.setData(updatemdoel);
      })
      return;
    },
    //返回
    Backfunc(e) {
      if (this.data.mode == 2) {
        this.setData({
          op: "result"
        });
      } else {
        wx.navigateBack({
          delta: 1
        })
      }

    },
    //点击显示收货地址列表
    showselect: function () {
     
      this.getpagelist(this, 1)
      this.setData({
        op: "list"
      })
    },
    //初始化
    set_init(navCur) {  
      
      var app = getApp();
      var that = this;     
      if (app.globalData && app.globalData.Custom) {
        var updatepara = {
          Custom: app.globalData.Custom,
          CustomBar: app.globalData.CustomBar,
          op: "result",    
          navCur     
        }
        //选中默认地址
      
        if (this.data.selectdefault) {
          var addr=app.globalData.addr
        
          if (!addr||(navCur==3 && !addr.lat)) {
            addrbill.mydefalut(navCur).then(function (params) {
        
       

              if (params["status"] == 1) {
                params["obj"] = that.calculatiodistance( params["obj"],navCur )
                that.setData({
                  selectaddr: params["obj"]
                })
                // if(navCur==3&& params["obj"]["lat"]){
                //   params["obj"]
                // }
                that.triggerEvent("selectaddr",   params["obj"])
              } else { 

                that.setData({
                  selectaddr: {}
                })
                that.triggerEvent("selectaddr",   null)
              }
            })
          } else {
            //增加距离
            addr= that.calculatiodistance( addr,navCur )
            updatepara["selectaddr"] = addr;
            this.triggerEvent("selectaddr",  addr)
          }
        }
        this.setData(updatepara);
      }
    },    

    calculatiodistance(addr,navCur){
     

      var intracity =this.data.delivery_config.intracity;      
       if(navCur==3){
        addr["distance"] =   app.toolv2.distanceByLnglat(addr.lng,addr.lat,intracity.lng,intracity.lat)
       }
       return addr
    },
    // 选择编辑导入增加地址
    optool(e) {
      var dataset = e.currentTarget.dataset;
      var addform = this.selectComponent("#addform");
      var idx = dataset.idx;
      var that = this;
      var updatemodel = {};
      switch (dataset.op) {
        case "del": {
          var model = this.data.addrlist[idx];
          var that = this;
          wx.showModal({
            title: '删除',
            content: "删除 " + model.name + "[" + model.phone + "]",
            showCancel: true,
            success(res) {
              if (res.confirm) {
                addrbill.del(model.id).then(function (vdata) {
                  if (vdata["status"] == 1) {

                    that.data.addrlist.splice(idx, 1);

                    that.setData({ addrlist: that.data.addrlist });
                    wx.showToast({
                      title: '删除成功'
                    })
                  }
                })

              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          break;

        }
        case "edit": {
          addform.showop(dataset.op, this.data.addrlist[idx]);     
          updatemodel["acteq"] = idx;
          updatemodel["op"] = dataset.op;
          this.setData(updatemodel)
          break;
        }
        case "add": {
          if (dataset.form == "choose") {
            wx.chooseAddress({
              success: function (res) {

                addrbill.wxaddrtosysaddr(res).then(function(myaddr){
                
                  var addrmodel = { id: 0 }
                  addrmodel["province"] = res.provinceName;
                  addrmodel["county"] = res.countyName;
                  addrmodel["city"] = res.cityName;
                  addrmodel["name"] = res.userName;
                  addrmodel["addrinfo"] =  res.cityName +res.countyName + res.detailInfo;
                  addrmodel["phone"] = res.telNumber;
                  addrmodel["isdefault"] = -1
                  updatemodel["op"] = dataset.op;
                  if (myaddr) {                    
                    var ilen = myaddr.length
                    if (myaddr.length < 3) {
                      for (; ilen < 3; ilen++) {
                        myaddr.push({ id: "", name: "" })
                      }
                    }
                    addrmodel["region"] = myaddr;
                    addrmodel["provincecode"] = myaddr[0]["id"];
                    addrmodel["citycode"] = myaddr[1]["id"];
                    addrmodel["countycode"] = myaddr[2]["id"];
                  }
                  that.setData(updatemodel)
                  addform.showop(dataset.op, addrmodel);
                })
                
              }
            })
          }
          else {
            addform.showop(dataset.op, null);
            updatemodel["op"] = dataset.op;
            this.setData(updatemodel)
          }
          break;
        }
        case "setdefault": {
          var selectmodel = this.data.addrlist[idx];
          addrbill.setdefalut(selectmodel.id, -selectmodel.isdefault).then(function (params) {
            if (params["status"] == 1) {
            }
          })
          if (selectmodel.isdefault == -1) {
            for (var ia in this.data.addrlist) {
              if (this.data.addrlist[ia].isdefault == 1) {
                updatemodel["addrlist.[" + ia + "].isdefault"] = -1;
                break;
              }
            }

            updatemodel["addrlist.[" + idx + "].isdefault"] = 1;
          }else{
            updatemodel["addrlist.[" + idx + "].isdefault"] = -1;

          }
         
          this.setData(updatemodel)
          break;
        }
        case "close": {
          this.setData({ op: "list" })
          break;
        }
      }
    },
//  增加后更新列表
    addreditblack(e) {
      var addrmodel = e.detail
      var op = this.data.op;
      var that = this;
      var addrlist = that.data.addrlist
      if (op == "add") {
        addrlist.splice(0, 0, addrmodel)
      }
      if (addrmodel.isdefault == 1) {
        for (var a in addrlist) {
          if (addrlist[a].id != addrmodel.id) {
            addrlist[a].isdefault = -1
          }
        }
      }
      var updatemodel = {}
      updatemodel["addrlist"] = addrlist;
      this.setData(updatemodel)
    },
    //选择当前地址
    selecteditem(e) {
      if (this.data.mode == 2) {
        var dataset = e.currentTarget.dataset;
        var selectaddr = this.data.addrlist[dataset["idx"]];         
        var app = getApp();
        if(this.data.navCur == 3){
          if(selectaddr.lat==0|| !selectaddr.lat){
            wx.showToast({
              title: '请先完善信息',
            })

            return ;
          }
          else
          {
            var intracity =this.data.delivery_config.intracity; 
            selectaddr["distance"] =   app.toolv2.distanceByLnglat(selectaddr.lng,selectaddr.lat,intracity.lng,intracity.lat)
          
       
            if(selectaddr["distance"].val -intracity["maxdistance"]>0){            
              wx.showToast({
                title: '配送范围之外',
              })
              return ;
            }    

          }          
        }     
        
        app.globalData.addr = selectaddr;
        this.setData({
          selectaddr: selectaddr,
          op: "result",
        })

        

        var myEventDetail = selectaddr // detail对象，提供给事件监听函数
        var myEventOption = {} // 触发事件的选项
        this.triggerEvent("selectaddr", myEventDetail, myEventOption)
      }
    },

  getnoaddrdata:function(ev){

    var noaddrcom = this.selectComponent("#noaddrcom");
     var reslut =noaddrcom.getaddrmodel()  
     if(reslut)
     {
       return reslut;
     }
     return false;
   
  },

    //关闭添加收货地址弹窗
    closeaddrblock: function () {
      this.setData({
        addrblock: true
      })
    },
 
    

  }
})